package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/send4Order")
    public Result send4Order(String telephone) {
        return sendSMS(telephone, 4, RedisMessageConstant.SENDTYPE_ORDER);
    }

    @RequestMapping("/send4Login")
    public Result send4Login(String telephone) {
        //获取手机登陆验证码
        return sendSMS(telephone, 6, RedisMessageConstant.SENDTYPE_LOGIN);
    }

    private Result sendSMS(String telephone, int i, String sendtypeOrder) {
        //获取随机验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(i);
        try {
            //给用户手机发送验证码短信
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, validateCode.toString());
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //验证码存到缓存5分钟//给手机号加一个标识，确保得到的手机号不会重复
        Jedis jedis = jedisPool.getResource();
        jedis.setex(telephone + sendtypeOrder, 30000, validateCode.toString());
        jedis.close();

        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
